﻿/// <reference path="../main.html" />
require([
    "jquery",
    "jquery-migrate",
    "bootstrap",
    "jquery-blockui",
    "jquery-validation",
    "jquery-backstretch",
    "jquery-select2",
    "jquery-qrcode",
    "akcy"
], function ($) {
    var akcy = arguments[arguments.length - 1];
    var v = window.location.toString().getUrlParm("v");
    if (v == "" || v == undefined) {
        window.location = "/";
    }
    var index = function () {

        var handleSession = function () {
            var sessionid = akcy.session.get();
            if (sessionid != undefined && sessionid != "") {
                akcy.ajaxpostsilent("/ak56api/home/checklogin?sessionid=" + sessionid).done(function (rst) {
                    if (rst != undefined && rst.status)
                    {
                        akcy.currentuser.set(rst.name);
                        $("#login-alert span").html("您已登录，正在跳转...");
                        $("#login-alert").removeClass("alert-danger").addClass("alert-success").slideDown(function () {
                            setTimeout(function () {
                                window.location = "/application/home/main.html?v=" + v;
                            }, 1500);
                        });
                    }
                });
            }
        }

        var handleLogin = function () {
            var rb = akcy.cookie("ak56_remember");
            if (rb != undefined && rb != "") {
                $('.login-form input[name="remember"]').prop("checked", true);
                $('.login-form input[name="username"]').val(rb);
            }

            $('.login-form').validate({
                errorElement: 'span',
                errorClass: 'help-block',
                focusInvalid: false,
                rules: {
                    username: {
                        required: true
                    },
                    password: {
                        required: true
                    },
                    remember: {
                        required: false
                    }
                },
                messages: {
                    username: {
                        required: "请您输入帐号！"
                    },
                    password: {
                        required: "请您输入密码！"
                    }
                },

                invalidHandler: function (event, validator) {
                    $('.alert-danger', $('.login-form')).slideDown();
                },

                highlight: function (element) {
                    $(element)
	                    .closest('.form-group').addClass('has-error');
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                    label.remove();
                },

                errorPlacement: function (error, element) {
                    error.insertAfter(element.closest('.input-icon'));
                },

                submitHandler: function (form) {
                    $("#login-alert span").html("正在登录，请稍等...");
                    $("#login-alert").removeClass("alert-danger").addClass("alert-success").slideDown("normal", function () {
                        var username = $(form["username"]).val();
                        var password = $(form["password"]).val();
                        var remember = $(form["remember"]).is(":checked");

                        akcy.ajaxpostsilent("/ak56api/home/login?username=" + username + "&password=" + password).done(function (rst) {
                            $("#login-alert span").html("登录成功，跳转中...");
                            $("#login-alert").removeClass("alert-danger").addClass("alert-success").slideDown("normal", function () {
                                $.when(akcy.session.set(rst), akcy.currentuser.set(username)).done(function () {
                                    if (remember) {
                                        akcy.cookie("ak56_remember", username);
                                    }
                                    else {
                                        akcy.cookie("ak56_remember", "");
                                    }

                                    setTimeout(function () {
                                        window.location = "/application/home/main.html?v=" + v;
                                    }, 1500);
                                });
                            });
                        }).fail(function () {
                            $("#login-alert").removeClass("alert-success").addClass("alert-danger").slideDown();
                            var msg = "无法连接到服务器！";
                            if (arguments[0].responseJSON != undefined && arguments[0].responseJSON != "") {
                                msg = arguments[0].responseJSON;
                            }
                            $("#login-alert span").html(msg);
                        });

                    });
                }
            });

            $('.login-form input').keypress(function (e) {
                if (e.which == 13) {
                    if ($('.login-form').validate().form()) {
                        $('.login-form').submit();
                    }
                    return false;
                }
            });


        }

        var handleForgetPassword = function () {
            $('.forget-form').validate({
                errorElement: 'span',
                errorClass: 'help-block',
                focusInvalid: false,
                ignore: "",
                rules: {
                    email: {
                        required: true,
                        email: true
                    }
                },

                messages: {
                    email: {
                        required: "Email is required."
                    }
                },

                invalidHandler: function (event, validator) {

                },

                highlight: function (element) {
                    $(element)
	                    .closest('.form-group').addClass('has-error');
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                    label.remove();
                },

                errorPlacement: function (error, element) {
                    error.insertAfter(element.closest('.input-icon'));
                },

                submitHandler: function (form) {
                    form.submit();
                }
            });

            $('.forget-form input').keypress(function (e) {
                if (e.which == 13) {
                    if ($('.forget-form').validate().form()) {
                        $('.forget-form').submit();
                    }
                    return false;
                }
            });

            jQuery('#forget-password').click(function () {
                jQuery('.login-form').hide();
                jQuery('.forget-form').show();
            });

            jQuery('#back-btn').click(function () {
                jQuery('.login-form').show();
                jQuery('.forget-form').hide();
            });

        }

        var handleRegister = function () {

            function format(state) {
                if (!state.id) return state.text;
                return "<img class='flag' src='/global/img/flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
            }


            $("#select2_sample4").select2({
                placeholder: '<i class="fa fa-map-marker"></i>&nbsp;Select a Country',
                allowClear: true,
                formatResult: format,
                formatSelection: format,
                escapeMarkup: function (m) {
                    return m;
                }
            });


            $('#select2_sample4').change(function () {
                $('.register-form').validate().element($(this));
            });



            $('.register-form').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                rules: {

                    fullname: {
                        required: true
                    },
                    email: {
                        required: true,
                        email: true
                    },
                    address: {
                        required: true
                    },
                    city: {
                        required: true
                    },
                    country: {
                        required: true
                    },

                    username: {
                        required: true
                    },
                    password: {
                        required: true
                    },
                    rpassword: {
                        equalTo: "#register_password"
                    },

                    tnc: {
                        required: true
                    }
                },

                messages: { // custom messages for radio buttons and checkboxes
                    tnc: {
                        required: "Please accept TNC first."
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   

                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
	                    .closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                    label.remove();
                },

                errorPlacement: function (error, element) {
                    if (element.attr("name") == "tnc") { // insert checkbox errors after the container                  
                        error.insertAfter($('#register_tnc_error'));
                    } else if (element.closest('.input-icon').size() === 1) {
                        error.insertAfter(element.closest('.input-icon'));
                    } else {
                        error.insertAfter(element);
                    }
                },

                submitHandler: function (form) {
                    form.submit();
                }
            });

            $('.register-form input').keypress(function (e) {
                if (e.which == 13) {
                    if ($('.register-form').validate().form()) {
                        $('.register-form').submit();
                    }
                    return false;
                }
            });

            jQuery('#register-btn').click(function () {
                jQuery('.login-form').hide();
                jQuery('.register-form').show();
            });

            jQuery('#register-back-btn').click(function () {
                jQuery('.login-form').show();
                jQuery('.register-form').hide();
            });
        }

        var handleQrCookie = function () {
            akcy.ajaxpostsilent("/qrgenerationforlogin").done(function (rst) {
                $('#qrc canvas').qrcode({
                    'text': rst.url
                });
                akcy.cookie('ak_qrcode', rst.sessionId);
            });
        }

        return {

            init: function () {
                handleSession();
                handleLogin();
                handleForgetPassword();
                handleRegister();
                handleQrCookie();
            }

        };

    }();

    akcy.ui.init();
    index.init();

    var tryCount = 0;
    var isStartCheckQRL = false;
    function startCheckQRL() {
        if (!isStartCheckQRL) {
            checkQRL();
            isStartCheckQRL = true;
        }
    }

    var checkQRL = function () {
        akcy.ajaxpostsilent("/checkqrcode?sessionId=" + akcy.cookie('ak_qrcode')).done(function (rst) {
            if (rst.Status == 1) {
                tryCount = 0;
                isStartCheckQRL = false;
                //登录成功
                $.when(akcy.session.set(rst.SessionID), akcy.currentuser.set(rst.LoginName)).done(function () {
                    window.location = "/application/home/main.html?v=" + v;
                });
            } else if (tryCount >= 100) {
                tryCount = 0;
                isStartCheckQRL = false;
                jQuery('.login-form').show();
                jQuery('#qrc').hide();
            } else {
                tryCount++;
                setTimeout(checkQRL, 2000);
            }
        });
    }

    jQuery('#showqrlogin').click(function () {
        startCheckQRL();
        jQuery('.login-form').hide();
        jQuery('#qrc').show();
    });

    jQuery('#shownamelogin').click(function () {
        jQuery('.login-form').show();
        jQuery('#qrc').hide();
    });


    $.backstretch([
     "/Application/Global/Img/bg/1.jpg",
     "/Application/Global/Img/bg/2.jpg",
     "/Application/Global/Img/bg/3.jpg",
     "/Application/Global/Img/bg/4.jpg",
    ], {
        fade: 1000,
        duration: 8000
    });
});